require('mm_expand');
const Koa = require('koa');
const fs = require('fs');
const Router = require('koa-router');
const parser = require('koa-parser');

const { accessLogger, logger } = require('./middlewares/log4js');
const catchError = require('./middlewares/exception')

const router = new Router();

// 读取配置文件
const text = fs.readFileSync('./config.json');
// 反序列化
const config = JSON.parse(text);

// 创建app 实例
const app = new Koa();

// 解构配置文件
const { port, host } = config.web;

app.use(parser());
// log4js 中间件
app.use(accessLogger());
// 异常处理中间件
app.use(catchError);

// 错误监听
app.on('error', err => {
  logger.error('app error' + err)
})
// 遍历出所有services 目录下所有的 .service.js 文件
const serviceFile = $.file.getAll('./services'.fullname(__dirname), '*.service.js');

// 声明一个空的 对象用于函数传递
const services = {}


// 循环调用service 方法
for (let f of serviceFile) {
  const service = require(f);
  service(services);
}

// 遍历路由
const routersFile = $.file.getAll('./router'.fullname(__dirname), '*.router.js');
// 循环调用
for (let f of routersFile) {
  const route = require(f);
  route(router, services);
}


app.use(router.routes());

app.listen(port, host, () => {
  console.log(`listening on:  http://${host}:${port}`)
})
